package server.command.list;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;

import communication.exception.ResultException;
import communication.exception.VerifyParameterException;

import server.command.AnalysisCommand;
import server.command.Command;
import server.core.base.Airport;
import server.core.base.Flight;
import server.core.dao.DaoFactory;
import server.core.dao.MemoryDAO;
import server.core.manager.Admin;
import server.core.manager.Manager;
import server.core.util.FormatDate;

public class SaveFlight implements Command {
	private AnalysisCommand parsing;
	@Override
	public Collection<Object> execute() throws ResultException {
		Collection<Object> result=new LinkedList<Object>();
		long id=DaoFactory.getDao(parsing.getTypeOfDao()).saveObject(new Flight(
				(Airport) parsing.getArgsMap().get("FROMPORT"),
				(Airport) parsing.getArgsMap().get("TOPORT"),
				(FormatDate) parsing.getArgsMap().get("DATE")
				));
		if(id==0)
			throw new ResultException("Flight adding error");
		result.add(id);
		result.add("-id added!");
		return result;
	}

	@Override
	public void verifyParam(AnalysisCommand parsing) throws VerifyParameterException {
		this.parsing=parsing;
		Iterator<?> itr;
		for(String key:AnalysisCommand.paramAirport){
			if(parsing.getParamMap().containsKey(key)){
				itr=((MemoryDAO) DaoFactory.getDao(parsing.getTypeOfDao())).getEntityMap(Airport.class).values().iterator();
				while(itr.hasNext()){
					Airport port=(Airport) itr.next();
					if(port.getTitle().equalsIgnoreCase(parsing.getParamMap().get(key)))
						parsing.getArgsMap().put(key, port);
				}
				if( ! parsing.getArgsMap().containsKey(key))
					throw new VerifyParameterException("Unknown airport`s code in #"+key);
			}
			else
				throw new VerifyParameterException(
						"Parameter is missing #"+key);
		}
		for(String key:AnalysisCommand.paramDate){
			if(parsing.getParamMap().containsKey(key))
				parsing.getArgsMap().put(key,parsing.changeStringIntoDate(parsing.getParamMap().get(key)));
			else
				throw new VerifyParameterException("Parameter is missing #"+key);
		}
	}

	@Override
	public String help() {
		return " fromPort= toPort= date=";
	}

	@Override
	public Class<? extends Manager> getManager() {
		return Admin.class;
	}

	@Override
	public void exit() {
		// TODO Auto-generated method stub
		
	}

}
